﻿#-*- encoding: utf-8 -*-

import Image, pyexiv2
import glob, os


def resize_image(source_path, dest_path, size):
	# resize image
	image = Image.open(source_path)
	image.thumbnail(size, Image.ANTIALIAS)
	image.save(dest_path, quality=100)
	image = Image.open(dest_path)

	# copy EXIF data
	source_meta = pyexiv2.ImageMetadata(source_path)
	source_meta.read()
	dest_meta = pyexiv2.ImageMetadata(dest_path)
	dest_meta.read()
	
	# set EXIF image size info to resized size
	source_meta["Exif.Photo.PixelXDimension"] = image.size[0]
	source_meta["Exif.Photo.PixelYDimension"] = image.size[1]
	image = 0
	source_meta.copy(dest_meta)
	dest_meta.write()
	
def main():
	in_dir = './in/'
	out_dir = './out/'

	if not os.path.exists(in_dir):
		print "in not exists"
	if not os.path.exists(out_dir):
		os.mkdir(out_dir)

	infiles = glob.glob(in_dir+'*.jpg')

	size = 3000, 3000

	for infile in infiles:
		print 'file: ' + os.path.split(infile)[1]
		print 'dir:' + os.path.split(infile)[0]
		outfile = out_dir + os.path.split(infile)[1]
		try:
			resize_image(infile, outfile, size)
		except IOError:
			print "cannot create thumbnail for", infile
			
if __name__ == "__main__":
	main()